package com.java.test.JVM;

import java.lang.ref.SoftReference;

public class ExampleSoftRef {
    public static class A{

    }
    public static class B{
        private A strongRef;

        public void setStrongRef(A ref) {
            this.strongRef = ref;
        }
    }
    public static SoftReference<A> cache;

    public static void main(String[] args) throws InterruptedException{
        //initialisation of the cache with a soft reference of instanceA
        ExampleSoftRef.A instanceA = new ExampleSoftRef.A();
        cache = new SoftReference<ExampleSoftRef.A>(instanceA);
        instanceA=null;
        // instanceA  is now only soft reachable and can be deleted by the garbage collector after some time
        Thread.sleep(5000);

        ExampleSoftRef.B instanceB = new ExampleSoftRef.B();
        //since cache has a SoftReference of instance A, we can't be sure that instanceA still exists
        //we need to check and recreate an instanceA if needed
        instanceA=cache.get();
        if (instanceA ==null){
            instanceA = new ExampleSoftRef.A();
            cache = new SoftReference<ExampleSoftRef.A>(instanceA);
        }
        instanceB.setStrongRef(instanceA);
        instanceA=null;
        // instanceA a is now only softly referenced by cache and strongly referenced by B so it cannot be cleared by the garbage collector
    }
}
